<template>
	<view class="container">
		<view class="header">
			<view class="center">
				<view class="store">
					<view class="title">
						<image src="/static/menu/店面.jpg" class="storefront"></image>
						<!-- 为了测试方便，这里使用静态店铺数据 -->
						<view class="information">
							<view class="storename">{{ '洞庭渔' }}</view>
							<view class="address">{{ '地址：桂林科大花江店' }}</view>
							<view class="contact">{{ '联系我们：000-000-001' }}</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 滚动公告栏 begin -->
			<view class="notices">
				<swiper class="swiper" autoplay vertical :interval="3000" :duration="1000" circular>
					<swiper-item v-for="(notice, index) in notices" :key="index">
						<view class="swiper-item">
							<image :src="notice.image" class="image"></image>
							<view class="content">{{ notice.content }}</view>
						</view>
					</swiper-item>
				</swiper>
			</view>
		</view>
<!-- 		<u-button shape="circle" type="primary" @click="openTableDialog" style="width: 90%;">
		  {{ selectedTable ? '已选' + selectedTable.tableId + '餐桌' : '选择餐桌' }}
		</u-button>
		<u-button shape="circle" type="primary" @click="cancelTableSelection" v-if="selectedTable" style="width: 90%;">取消所选餐桌</u-button> -->
		<!-- <u-popup v-model="dialogVisible" position="bottom"  :z-index="1000" mode="bottom"
			close-icon-pos="top-right" border-radius="14" closeable="true">
			<scroll-view class="dialog-content" scroll-y style="max-height: 300px;">
				<view class="table-item" v-for="table in tableData" :key="table.tableId" @click="selectTable(table)">
					<text>{{ table.tableId }}号餐桌</text>
					<text v-if="selectedTable === table">已选</text>
				</view>
			</scroll-view>
			<u-button type="primary" @click="confirmTableSelection">
			  {{ selectedTable ? '选择' + selectedTable.tableId + '号餐桌' : '确定' }}
			</u-button>
		</u-popup> -->
		<view class="main">
			<scroll-view class="menu-bar" scroll-y scroll-with-animation v-model="showMenu">
				<view class="wrapper">
					<view class="menu-item" @tap="handleMenuSelected(category.id)"
						:class="{active: currentCategoryId == category.id}" v-for="(category, index) in categories"
						:key="index">
						<image :src="category.category_image_url" class="image" mode="widthFix"></image>
						<view class="title">{{ category.name }}</view>
					</view>
				</view>
			</scroll-view>
			<scroll-view class="product-section" scroll-y scroll-with-animation :scroll-top="productsScrollTop"
				@scroll="productsScroll">
				<view class="wrapper">
					<view id="ads">
						<!-- 广告栏1 begin -->
						<swiper class="ads1" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000"
							circular>
							<swiper-item v-for="(ad, index) in ads1" :key="index">
								<image :src="ad" class="w-100" mode="widthFix"></image>
							</swiper-item>
						</swiper>
						<!-- 广告栏1 end -->
						<!-- 广告栏2 begin -->
						<swiper class="ads2" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000"
							circular>
							<swiper-item v-for="(ad, index) in ads2" :key="index">
								<image :src="ad" class="w-100" mode="widthFix"></image>
							</swiper-item>
						</swiper>
					</view>
					<!-- 广告栏2 end -->
					<!-- 商品 begin -->
					<view class="products-list" v-for="(category, index) in categories" :key="index"
						:id="`products-${category.id}`">
						<view class="category-name">{{ category.name }}</view>
						<view class="products">
							<view class="product" v-for="(product, key) in category.products" :key="key"
								@tap="showProductDetailModal(product)">
								<image :src="product.menuImage" mode="widthFix" class="image"></image>
								<view class="content">
									<view class="name">{{ product.menuName }}</view>
									<!-- 									<view class="labels">
																<view class="label"
																:style="{color: label.label_color, background: $util.hexToRgba(label.label_color, 0.2)}"
																 v-for="label in product.labels" :key="label.id">{{ label.name }}</view>
															</view> -->
									<!-- <view class="description">{{ product.description }}</view> -->
									<view class="price">
										<view>￥{{ product.menuPrice }}</view>
										<actions :materials-btn="!product.is_single"
											@materials="showProductDetailModal(product)"
											:menuNumber="productCartNum(product.menuId)" @add="handleAddToCart(product)"
											@minus="handleMinusFromCart(product)" />
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 商品 end -->
				</view>
			</scroll-view>
		</view>
		<product-modal :product="product" :visible="productModalVisible" @cancel="closeProductDetailModal"
			@add-to-cart="handleAddToCartInModal" />
		<!-- 商品详情 modal end -->
		<!-- 购物车栏 begin -->
		<cart-bar :cart="cart" @add="handleAddToCart" @minus="handleMinusFromCart" @clear="clearCart" @pay="pay" />
		<search :show="showSearch" :categories="categories" @hide="showSearch=false" @choose="showProductDetailModal">
		</search>
	</view>
</template>

<script>
	import Actions from './components/actions/actions.vue'
	import CartBar from './components/cartbar/cartbar.vue'
	import ProductModal from './components/product-modal/product-modal.vue'
	import cartPopup from './components/cart-popup/cart-popup.vue'
	import Search from './components/search/search.vue'
	import {
		requst_get_menuInfo
	} from '@/api/menu.js'
	export default {
		components: {
			Actions,
			CartBar,
			ProductModal,
			cartPopup,
			Search,
		},
		data() {
			return {
				dialogVisible: false,
				tableData: [],
				categories: [],
				currentPage: 1,
				pageSize: 10,
				currentCategoryId: 0,
				showSearch: false,
				orderType: 'takein',
				notices: [],
				disabled: true,
				productsScrollTop: 0,
				product: {},
				cart: [],
				productModalVisible: false,
				cartPopupShow: false,
				selectedTable: uni.getStorageSync('selectedTable'),
				showMenu: false,
				ads1: [
					"https://st-gdx.dancf.com/gaodingx/0/uxms/design/20200310-202156-d9a1.png?x-oss-process=image/resize,w_1125/interlace,1,image/format,jpg",
					"https://img.zcool.cn/community/01ea4a554317980000019ae999aa13.jpg@1280w_1l_2o_100sh.jpg",
					"https://tse3-mm.cn.bing.net/th/id/OIP-C.BPdQ8qmBHxRgGXi_pMp6jAHaDJ?rs=1&pid=ImgDetMain",
					"https://go.cdn.heytea.com/storage/ad/2020/05/21/b88c6780a73249b0b0166784917a5046.jpg"
				],
				ads2: [
					"https://go.cdn.heytea.com/storage/ad/2020/05/21/acfc6504f3074cf6b730f516adc558f6.jpg",
					"https://go.cdn.heytea.com/storage/ad/2020/04/26/2373600789c64752b2415293877ead40.jpg",
					"https://go.cdn.heytea.com/storage/ad/2020/04/22/515df8c726e740089ae4c55582b4ce09.jpg",
					"https://go.cdn.heytea.com/storage/ad/2020/04/14/d0e51cb22c0a437293c0e6a879b59c7d.jpg"
				],
			};
		},
		computed: {
			async onLoad() {
				this.notices = await this.$api('notices')
				// this.categories = await this.$api('categories')
				// this.currentCategoryId = this.categories.length && this.categories[0].id
				this.$nextTick(() => this.calcSize())
			},
		},
		created() {
			requst_get_menuInfo(null).then(res => {
				res = res.data;
				if(res.code == 200){
					this.categories = res.data; // 将数据存储到 this.categories
					this.currentCategoryId = this.categories.length && this.categories[0].id
					console.log(this.currentCategoryId); // 打印数据
					}
			});
		},
		methods: {
			productCartNum(menuId) { // 计算单个饮品添加到购物车的数量
				return this.cart.reduce((acc, cur) => {
					if (cur.menuId === menuId) {
						return acc + cur.menuNumber; // 累加数量
					}
					return acc;
				}, 0);
			},

			switchOrderType() {
				if (this.orderType === 'takein') {
					uni.navigateTo({
						url: '/pages/addresses/addresses'
					})
				} else {
					this.SET_ORDER_TYPE('takein')
				}
			},
			handleTableSelected(table) {
				// 处理选择餐桌的逻辑，将选中的餐桌信息存储在 selectedTable 变量中
				this.selectedTable = table;
				// 设置 showMenu 变量为 true，显示下面的菜单
				this.showMenu = true;
			},
			handleMenuSelected(id) {
				this.productsScrollTop = this.categories.find(item => item.id == id).top
				console.log(this.currentCategoryId);
				this.$nextTick(() => this.currentCategoryId = id)
			},
			closeProductDetailModal() {
				this.productModalVisible = false
				this.product = {}
			},
			showProductDetailModal(product) {
				this.product = product
				this.productModalVisible = true
			},
			handleAddToCartInModal(product) {
				this.handleAddToCart(product)
				this.closeProductDetailModal()
			},
			handleAddToCart(product) { //添加到购物车
				const index = this.cart.findIndex(item => {
					if (!product.is_single) {
						return (item.menuId == product.menuId) && (item.materials_text == product.materials_text);
					} else {
						return item.menuId === product.menuId;
					}
				});

				// 检查是否已经存在于购物车
				if (index > -1) {
					// 如果项目已经存在于购物车，增加数量
					this.cart[index].menuNumber += (product.number || 1);
					return
				}
				// 否则，将新项目添加到购物车
				this.cart.push({
					menuId: product.menuId,
					cate_id: product.category_id,
					menuName: product.menuName,
					menuPrice: product.menuPrice,
					menuNumber: product.number || 1,
					image: product.menuImage,
					is_single: product.is_single,
					materials_text: product.materials_text || ''
				})
			},

			handleMinusFromCart(product) { //从购物车减商品
				let index
				if (product.is_single) {
					index = this.cart.findIndex(item => item.menuId == product.menuId)

				} else {
					index = this.cart.findIndex(item => (item.menuId == product.menuId) && (item.materials_text == product
						.materials_text))
				}
				this.cart[index].menuNumber -= 1
				if (this.cart[index].menuNumber <= 0) {
					this.cart.splice(index, 1)
				}
			},
			openCartDetailsPopup() {
				this.$refs['cartPopup'].open()
			},
			calcSize() {
				let h = 0
				let view = uni.createSelectorQuery().select('#ads')
				view.fields({
					size: true
				}, data => {
					h += Math.floor(data.height)
				}).exec()

				this.categories.forEach(item => {
					let view = uni.createSelectorQuery().select(`#products-${item.id}`)
					view.fields({
						size: true
					}, data => {
						item.top = h
						h += Math.floor(data.height)
						item.bottom = h
					}).exec()
				})
			},
			productsScroll({
				detail
			}) {
				const {
					scrollTop
				} = detail
				let tabs = this.categories.filter(item => item.top <= scrollTop).reverse()
				if (tabs.length > 0) {
					this.currentCategoryId = tabs[0].id
				}
			},
			clearCart() {
				this.cart = []
			},
			pay() {
				uni.setStorageSync('selectedTable', this.selectedTable)
				uni.setStorageSync('cart', this.cart)
				uni.navigateTo({
					url: '/pages/pay/pay'
				})
			}
		},
	}
</script>

<style lang="scss">
	@import './index.scss';
</style>
